package utils

import (
	"gitee.com/shijun123456/kcgin"
	"gitee.com/shijun123456/srpcinterface/common"
	"github.com/garyburd/redigo/redis"
	"time"
)

//cache的实现者信息
var RedisConf = map[string]string{
	"name":    "redis",
	"type":    "tcp",
	"address": common.GenerateAddress(),
	"auth":    kcgin.AppConfig.String("redis.pass"),
}

//内部调用
var redisClient *redis.Pool

func init() {
	redisClient = &redis.Pool{
		//从配置文件中获取到信息 maxId maxActive 获取不到则用默认值
		MaxIdle:     kcgin.AppConfig.DefaultInt("redis.maxIdle", 50),
		MaxActive:   kcgin.AppConfig.DefaultInt("redis.maxActive", 500),
		IdleTimeout: time.Duration(kcgin.AppConfig.DefaultInt("redis.idleTimeout", 600)),
		Wait:        kcgin.AppConfig.DefaultBool("redis.wait", true),
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial(RedisConf["type"], RedisConf["address"], redis.DialDatabase(kcgin.AppConfig.DefaultInt("redis.db", 0)))
			if err != nil {
				return nil, err
			}
			if RedisConf["auth"] !=""{
				if _, err := c.Do("AUTH", RedisConf["auth"]); err != nil {
					return nil, err
				}
			}
			return c, nil
		},
	}
}

type RedisCache struct {
	redisPool *redis.Pool
}

func NewRedisCache() *RedisCache {
	return &RedisCache{}
}
func (r *RedisCache) Init() *RedisCache {
	r.redisPool = redisClient
	return r
}
func (r *RedisCache) Load(key string) (string, error) {
	rc := r.redisPool.Get()
	defer rc.Close()
	return redis.String(rc.Do("Get", key))
}
func (r *RedisCache) Set(key string, val string, expire int) error {
	rc := r.redisPool.Get()
	defer rc.Close()
	_, err := rc.Do("Set", key, val, "EX", expire)
	if err != nil {
		return err
	}
	return nil
}
